package com.foreverwin.jzymes.job;

import com.foreverwin.jzymes.common.constant.Constants;
import com.foreverwin.jzymes.common.domain.SysTask;
import com.foreverwin.jzymes.common.enums.TaskStatusEnum;
import com.foreverwin.jzymes.common.enums.TaskTypeEnum;
import com.foreverwin.jzymes.common.service.*;
import com.foreverwin.jzymes.common.util.BOHandleUtil;
import com.foreverwin.jzymes.common.util.CommonMethods;
import com.foreverwin.jzymes.framework.quartz.domain.SysJob;
import com.foreverwin.jzymes.framework.util.DateUtil;
import com.foreverwin.jzymes.framework.util.ObjectMapperUtil;
import com.foreverwin.jzymes.qc.check.domain.QcCheck;
import com.foreverwin.jzymes.qc.check.service.IQcCheckAdiviceService;
import com.foreverwin.jzymes.qc.check.service.IQcCheckService;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class TaskService {

    @Autowired
    ISystemRuleAdviceService systemRuleAdviceService;
    @Autowired
    IResourceAdviceService resourceAdviceService;
    @Autowired
    ICustomFieldsAdviceService customFieldsAdviceService;
    @Autowired
    ISysTaskService sysTaskService;
    @Autowired
    IItemGroupAdviceService itemGroupAdviceService;
    @Autowired
    IQcCheckService qcCheckService;
    @Autowired
    IQcCheckAdiviceService qcCheckAdiviceService;
    @Autowired
    ICommonService commonService;
    @Autowired
    JmsMessagingTemplate jmsTemplate;

    /**
     * 三次元任务创建入口
     *
     * @param job
     */
    public void createFAITask( SysJob job ){
        String site = job.getSite();

        List<String> workCenterHandleList = customFieldsAdviceService.findCustomFieldHandleList( site, Constants.WORK_CENTER_CUSTOM_FIELD_AUTOLINE, "Y" );

        for( String workCenterHandle : workCenterHandleList ){
            String workCenter = BOHandleUtil.splitWorkCenterHandle( workCenterHandle )[1];
            List<String> resourceList = resourceAdviceService.findResourceListByWorkCenter( site, workCenter );

            for( String resrce : resourceList ){

                if( resourceAdviceService.isCNC( site, resrce ) ){
                    /**创建qc检验任务*/
                    String taskId = createTask( site, TaskTypeEnum.FAI, resrce, "A" );

                    /**发送抽检指令*/
                    sendQcCheckCommand( site, resrce );
                }
            }
        }
    }

    /**
     * 目检任务创建入口
     *
     * @param job
     */
    public void createVITask( SysJob job ){

        String site = job.getSite();

        List<String> workCenterHandleList = customFieldsAdviceService.findCustomFieldHandleList( site, Constants.WORK_CENTER_CUSTOM_FIELD_AUTOLINE, "Y" );

        for( String workCenterHandle : workCenterHandleList ) {
            String workCenter = BOHandleUtil.splitWorkCenterHandle(workCenterHandle)[1];
            List<String> resourceList = resourceAdviceService.findResourceListByWorkCenter(site, workCenter);

            for (String resrce : resourceList) {

                if( resourceAdviceService.isCNC( site, resrce ) ){
                    /**创建qc检验任务*/
                    String taskId = createTask( site, TaskTypeEnum.VI, resrce, "A" );

                    /**发送抽检指令*/
                    sendQcCheckCommand( site, resrce );
                }
            }
        }
    }

    /**
     * 创建任务
     *
     * @param site
     * @param taskTypeEnum
     * @return
     */
    @Transactional( propagation = Propagation.REQUIRED )
    public String createTask( String site, TaskTypeEnum taskTypeEnum, String resource, String createType ){

        /**检查设备任务类型存在未完成的任务，不再创建新的任务*/
        List<QcCheck> openQcCheckList = qcCheckAdiviceService.findOpenQcCheck( site, taskTypeEnum, resource );
        if( openQcCheckList != null && openQcCheckList.size() > 0 ){
            return openQcCheckList.get(0).getTaskId();
        }

        String orderNumberRule = systemRuleAdviceService.existSystemRule( site, Constants.SYSTEM_RULE_TASK_NUMBER_RULE );
        String taskId = commonService.generateOrderNo( site, orderNumberRule );
        //String taskId = "T" + new Date().getTime();

        SysTask task = new SysTask();
        task.setSite( site );
        task.setTaskId( taskId );
        task.setTaskDesc( taskTypeEnum.desc() );
        task.setTaskType( taskTypeEnum.name() );
        task.setTaskStatus( TaskStatusEnum.OPEN.value() );
        task.setCreateType( createType );
        task.setCreatedDateTime( new Date() );
        task.setCreateUserBo( BOHandleUtil.buildUserHandle( site, CommonMethods.getUserId() ) );
        task.setHandle( BOHandleUtil.buildSysTaskHandle( task.getSite(), task.getTaskId() ) );
        sysTaskService.insertSysTask( task );

        QcCheck  qcCheck = new QcCheck();
        qcCheck.setSite( site );
        qcCheck.setTaskId( task.getTaskId() );
        qcCheck.setMachineType( itemGroupAdviceService.findItemGroupBySite( site ) );
        qcCheck.setResrce( resource );
        qcCheck.setCreatedDateTime( task.getCreatedDateTime() );
        qcCheck.setCreateUserBo( task.getCreateUserBo() );
        qcCheck.setHandle( BOHandleUtil.buildQcCheckHandle( qcCheck.getSite(), qcCheck.getTaskId() ) );
        qcCheckService.insertQcCheck( qcCheck );

        return taskId;
    }

    /**
     * 发送抽检指令
     *
     * @param resource
     */
    public void sendQcCheckCommand( String site, String resource ){

        /**检查工作中心自定义字段是否是自动线*/
        if( resourceAdviceService.isAutoLineResource( site, resource ) ){
            Map<String,Object> map = new HashMap<>();
            map.put( "MESSAGE_TYPE", "MES_QC_CHECK_COMMAND" );
            map.put( "TASK_ID", UUID.randomUUID().toString() );
            map.put( "RESRCE",resource  );
            map.put( "SEND_TIME", DateUtil.format( new Date(), "yyyy-MM-dd HH:mm:ss.SSS" ) );
            ActiveMQTopic topic = new ActiveMQTopic( "MES_QC_CHECK_COMMAND" );
            jmsTemplate.convertAndSend( topic, ObjectMapperUtil.writeValueAsString( map ) );
        }
    }
}
